﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Startup.MVVM;
using Startup.Shell.Domain;
using Startup.Shell.Domain.FunctionalityContracts;
using Startup.Shell.ModelDesignerPreview;

namespace Startup.Shell.Modules.PreviewDesignerCtrlModule
{
	public class PreviewDesignerCtrlModelView : ViewModelBase
	{
		private readonly StartupProject _startupProject;
		private readonly PreviewContainer _previewContainer;
	    private readonly StartupClass _domainClass;

		public PreviewDesignerCtrlModelView(StartupProject startupProject, PreviewContainer previewContainer, StartupClass domainClass)
		{
			_startupProject = startupProject;
			_previewContainer = previewContainer;
		    _domainClass = domainClass;

			_previewContainer.PreviewChanged += OnPreviewChanged;
		}

		public PreviewContainer PreviewContainer
		{
			get { return _previewContainer; }
		}

		private void OnPreviewChanged()
		{
			RaisePropertyChanged("Image");
			RaisePropertyChanged("PropertyName");
			RaisePropertyChanged("ImageVisibility");
			RaisePropertyChanged("PropertyVisibility");
		}

		public ImageSource Image
		{
			get
			{
				return _previewContainer.Preview == null ?
					new BitmapImage(new Uri("/Startup.Shell;component/Resources/EmptyScreen.png", UriKind.RelativeOrAbsolute)) :
					_previewContainer.Preview.PreviewImage;
			}
		}

		public bool ShowCommands
		{
			get { return _previewContainer.ShowCommands; }
		}

		public bool ShowPreview
		{
			get { return _previewContainer.ShowPreview; }
		}

		public ObservableCollection<CommandContractBase> Commands
		{
			get { return _previewContainer.Commands; }
		}

		public string PropertyName
		{
			get
			{
				if (_previewContainer.DataContextPropertyId == Guid.Empty) 
					return _domainClass.Name;
                
				StartupProperty property = _domainClass.FindProperty(_previewContainer.DataContextPropertyId);

				if (property != null)
					return property.Name;
				
				for (int index = 0; index < _startupProject.Classes.Count; index++)
				{
					StartupClass target = _startupProject.Classes[index];
					property = target.FindProperty(_previewContainer.DataContextPropertyId);

					if (property != null)
						return property.Name;
				}

				throw new Exception("There is unknown property id.");
			}
		}

		public static PreviewDesignerCtrlModelView Designer
		{
			get
			{
				return new PreviewDesignerCtrlModelView(new StartupProject(), new PreviewContainer { Preview = new WindowDesignerPreview() }, new StartupClass() { Name = "Domain"} );
			}
		}
	}
}
